package vip.meeet.jdk.concurent;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;


public class SendDataHelper {

    CopyOnWriteArrayList<String> msgPool = new CopyOnWriteArrayList<>();

    static int USE_THREAD_MIN_SLEEP_TIME = 99;

    static int useThreadSendTime = USE_THREAD_MIN_SLEEP_TIME;

    static int maxCacheMsgSize = 200;

    private AtomicBoolean isSending = new AtomicBoolean(false);

    private AtomicBoolean isRunning = new AtomicBoolean(true);

    private Thread sendThread = new Thread(() -> {
        while (isRunning.get()) {
            try {
                if (msgPool.size() == 0) {
                    Thread.sleep(useThreadSendTime);
                } else {
                    doSendPool();
                }
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    });

    private void sendSyn() {
        try {
            doSendPool();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            isSending.set(false);
        }
    }


    private void doSendPool() {
        while (msgPool.size() > 0) { //发送
            String message = msgPool.get(0);
            boolean suc = send(message);
            if (suc) {
                msgPool.remove(message);
            } else {
                break;
            }
        }
    }

    public void sendMsg(String message) {
        if (message == null) {
            return;
        }
        if (msgPool.size() >= maxCacheMsgSize) {
            return;
        }

        msgPool.add(message);
        if (useThreadSendTime > USE_THREAD_MIN_SLEEP_TIME) {
            if (isRunning.get() && Thread.State.NEW == sendThread.getState()) {
                sendThread.start();
            }
        } else {
            if (isSending.compareAndSet(false, true)) {
                sendSyn();
            }
        }
    }

    private boolean send(String data){
        System.out.println("网络数据发送逻辑");
        return true;
    }

}
